/********************************************************************************
 * @Author: Zhenzhou Liu
 * @Date: 2024-11-20
 * @Description: Cg图论练习之强连通分量
 *******************************************************************************/
#include <iostream>
#include <vector>

using namespace std;

vector<vector<int>> transpose(vector<vector<int>> &matrix) {
    int rows = matrix.size(), cols = matrix[0].size();
    vector<vector<int>> matT(cols, vector<int>(rows));
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matT[j][i] = matrix[i][j];
        }
    }
    return matT;
}

vector<int> DFS_Visit(vector<vector<int>> &graph, vector<bool> &visited, int i) {
    visited[i] = true;
    vector<int> list;
    int n = graph.size();
    for (int j = 0; j < n; ++j) {
        if (graph[i][j] && !visited[j]) {
            vector<int> temp = DFS_Visit(graph, visited, j);
            list.insert(list.end(), temp.begin(), temp.end());
        }
    }
    list.push_back(i);
    return list;
}

vector<int> DFS(vector<vector<int>> &graph) {
    int n = graph.size();
    vector<bool> visited(n, false);
    vector<int> list;
    for (int i = 0; i < n; ++i) {
        if (!visited[i]) {
            vector<int> temp = DFS_Visit(graph, visited, i);
            list.insert(list.end(), temp.begin(), temp.end());
        }
    }
    return list;
}

int stronglyConnectedComponentCount(vector<vector<int>> &graphMatrix) {
    vector<vector<int>> graphR = transpose(graphMatrix);
    int n = graphMatrix.size();
    vector<int> list = DFS(graphR);
    int count = 0;

    vector<bool> visited(n, false);
    for (int i = n - 1; i >= 0; --i) {
        if (!visited[list[i]]) {
            DFS_Visit(graphMatrix, visited, list[i]);
            ++count;
        }
    }
    return count;
}

int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> graphMatrix(n, vector<int>(n, 0));
    int u, v;
    for (int i = 0; i < m; ++i) {
        cin >> u >> v;
        graphMatrix[u - 1][v - 1] = 1;
    }
    cout << stronglyConnectedComponentCount(graphMatrix);
    return 0;
}

/*
Test Case1:
4 3
1 2
2 3
3 1

Test Case2:
10 15
1 3
1 10
2 6
3 4
3 7
4 1
4 6
5 2
6 5
7 7
8 9
8 10
9 7
9 8
10 1
*/
